<template lang="pug">
Form(:model='formData', :label-width=80)
  FormItem(label='标题', required)
    Input(v-model='formData.title')
  FormItem(label='发布时间')
    DatePicker(type='datetime',format='yyyy-MM-dd',placeholder='选择时间',clearable='ture',style='width: 200px',v-model='Time')
  FormItem(label='栏目', required)
    SelectCategory(module='article', :multiple='true', @change='setCategory')
  FormItem(label='文件', required)
    Upload(ref='upload',
      v-if='!file',
      multiple,
      action='javascript:;',
      :max-size='800',
      :show-upload-list='false',
      :before-upload='beforeUpload')
      Button(type='ghost', icon='ios-cloud-upload-outline') 选择文件
    //- Button(type='primary', @click='handleUpload') upload
    div(v-if='file')
      span {{ file.name }}
      Button(type='ghost', @click='file = null') 重新上传
  FormItem(label='置顶')
    i-switch(v-model='formData.sticky')
      Icon(type='android-done', slot='open')
      Icon(type='android-close', slot='close')
  FormItem.text-left
    Button(type='primary', @click='draft', :loading='loading1') 保存为草稿
    | &nbsp;&nbsp;
    Button(type='success', @click='publish', :loading='loading2') 发布
</template>

<script>
import CoverUploader from '@/components/CoverUploader'
import SelectCategory from '@/components/SelectCategory'

import Api from '@/apis/article'
import fileApi from '@/apis/file'
import store from '@/store'

export default {
  components: {
    CoverUploader,
    SelectCategory
  },
  data () {
    return {
      loading1: false,
      loading2: false,
      file: null,
      fileData: null,
      formData: {
        cover: null,
        title: '',
        fileId: '',
        group_id: store.state.app.id,
        category: [],
        published: true,
        sticky: false,
        created_timestamp: 0
      }
    }
  },
  computed: {
    Time: {
      get: function () {
        var myDate = new Date()
        function double (time) {
          if (time < 10)time = '0' + time
          return time
        }
        var formatDate = myDate.getFullYear() + '-' + double((myDate.getMonth() + 1)) + '-' + double(myDate.getDate())
        return formatDate
      },
      set: function (value) {
        var date = new Date(value.toString())
        if (isNaN(date.getFullYear()) || isNaN(date.getMonth()) || isNaN(date.getDate()) || isNaN(date.getHours()) || isNaN(date.getMinutes()) || isNaN(date.getSeconds())) {
          alert('日期错误')
        } else {
          this.formData.created_timestamp = date.getTime() / 1000
        }
      }
    }
  },
  methods: {
    validate () {
      return this.formData.title.trim() && this.formData.fileId
    },
    draft () {
      this.formData.published = false
      this.loading1 = true
      this.submit()
    },
    publish () {
      this.formData.published = true
      this.loading2 = true
      this.submit()
    },
    submit () {
      if (this.validate()) {
        // this.loading = true
        Api.postDownload(this.formData).then(() => {
          this.loading1 = false
          this.loading2 = false
          this.$router.push('/articles')
        })
      } else {
        this.loading1 = false
        this.loading2 = false
        this.$Message.error('请填写所需字段')
      }
    },
    setCategory (items) {
      this.formData.category = items.map(item => ({
        id: item.value,
        name: item.label
      }))
    },
    beforeUpload (file) {
      this.file = file
      console.log(file)

      let reader = new FileReader()
      reader.onload = e => {
        this.fileData = e.target.result
        // this.$forceUpdate()
        this.handleUpload()
      }
      reader.readAsDataURL(file)

      return false
    },
    async handleUpload () {
      try {
        let data = {
          filename: [{ value: this.file.name }],
          data: [{ value: this.fileData.replace(`data:${this.file.type};base64,`, '') }]
        }
        const res = await fileApi.uploadDocument(data)
        // console.log(res)
        if (res.status === 201 && res.data.fid[0].value) {
          this.formData.fileId = res.data.fid[0].value
          this.fileName = res.data.filename[0].value
        }
      } catch (e) {}
    }
  }
}
</script>
